import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_iot_plugin/flutter_iot_plugin.dart';
import 'package:flutter_iot_plugin/pigeon.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'package:getwidget/components/button/gf_button.dart';
import 'package:permission_handler/permission_handler.dart';

import 'add_device_controller.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  var _ssid = "";

  var iotResultStream = FlutterIotPlugin.instance.iotResultStreamController;

  var productKey = "a1T5Pde7XEc";
  var productId = "11379181";

  @override
  void initState() {
    super.initState();
    //监听原生调用FLutter
    initPlatformState();
    Get.lazyPut(() => AddDeviceController());

    iotResultStream.stream.listen((n) {
      // print("iotResultStream,success=${n.success}");
    });

    checkPermission();

  }

  @override
  void dispose() {
    super.dispose();
    iotResultStream.close();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      // String? everything = await FlutterIotPlugin.instance.getSSID();
      // platformVersion = everything ?? "";
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      // _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    final TextEditingController _wifiNameCtrl = TextEditingController(text: "wifi");
    final TextEditingController _wifiPasswordCtrl = TextEditingController(text: "lanshifu");
    _wifiNameCtrl.addListener(() {
      //输入变化
      print(_wifiNameCtrl.text);
    });
    final FocusNode _wifiNameFocusNode = FocusNode();
    final FocusNode _wifiPasswordFocusNode = FocusNode();
    var addDeviceState = AddDeviceController.instance.addDeviceState;
    var foundDeviceState = AddDeviceController.instance.foundDeviceState;
    // FlutterIotPlugin.instance.addDeviceListener = FlutterAliLink();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [

              GetBuilder<AddDeviceController>(builder: (controller) {
                return Text('step= ${addDeviceState.step}\n'
                );
              }),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.init(productKey, productId, _wifiNameCtrl.text, _wifiPasswordCtrl.text);
                  AddDeviceController.instance.startAddDeviceByBroadcast();
                },
                text: "一键配网",
              ),

              GFButton(
                onPressed: () {
                  AddDeviceController.instance.init(productKey, productId, _wifiNameCtrl.text, _wifiPasswordCtrl.text);
                  AddDeviceController.instance.startAddDeviceByBLE();
                },
                text: "蓝牙配网",
              ),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.stopAddDevice();
                },
                text: "停止配网",
              ),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.init(productKey, productId, _wifiNameCtrl.text, _wifiPasswordCtrl.text);
                  AddDeviceController.instance.startDiscovery();
                },
                text: "开始扫描",
              ),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.stopDiscovery();
                },
                text: "结束扫描",
              ),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.getDeviceToken(productKey);
                },
                text: "getDeviceToken",
              ),
              GFButton(
                onPressed: () {
                  AddDeviceController.instance.authCodeLogin(AddDeviceController.instance.addDeviceState.token.value);
                },
                text: "authCodeLogin",
              ),
              SizedBox(
                height: 200,
                child: GetBuilder<AddDeviceController>(
                  builder: (controller) {
                    return ListView.builder(
                      itemCount: foundDeviceState.foundDeviceInfos.length,
                      itemBuilder: (BuildContext context, int index) {
                        return GestureDetector(
                          child: ListTile(
                            title: Text("productKey:${foundDeviceState.foundDeviceInfos[index]?.productKey}"),
                            subtitle: Text("mac:${foundDeviceState.foundDeviceInfos[index]?.mac},linkType=${foundDeviceState.foundDeviceInfos[index]?.linkType}" ),
                          ),
                          onTapUp: (details) {
                            print("linkType :${foundDeviceState.foundDeviceInfos[index]?.linkType}");
                            print("productKey:${foundDeviceState.foundDeviceInfos[index]?.productKey}");
                            print("productId:${foundDeviceState.foundDeviceInfos[index]?.productId}");
                            //不用传参数的其实，只要判断
                            if(foundDeviceState.foundDeviceInfos[index]?.linkType == "ForceAliLinkTypeNone"){
                               AddDeviceController.instance.startAddDeviceByBroadcast();
                            } else {
                              AddDeviceController.instance.startAddDeviceByBLE();
                            }

                          },
                        );
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //判断是否有权限
  void checkPermission() async {
    Permission permission = Permission.locationAlways;
    PermissionStatus status = await permission.status;
    print('检测权限$status');
    if (status.isGranted) {
      //权限通过

    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面
      openAppSettings();
    } else if (status.isRestricted) {
      //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
      openAppSettings();
    } else {
      //第一次申请
      requestPermission(permission);
    }
  }

  //申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    print('权限状态$status');
    if (!status.isGranted) {
      openAppSettings();
    }
  }
}
